
import React from 'react';
import { message } from 'antd';
import _ from 'lodash';
import MemberList, { permissionList } from '../../components/MemberList';
import TitleItem from '../../components/TitleItem';
import HandleMemberSelect from '../common/handleMemberSelect';
import s from './member.module.less';

const opts = {
    setHost: 'ishost',
    setManager: 'ismanager'
}

class ProjectMember extends React.Component {

    state = {
        loading: false,
        showModal: false,
        activeKey: '',
        members0: [],
        members1: [],
        members2: [],
        isAdd: false,
    }

    componentWillMount() {
        this.handelSetValue(this.props);
    }

    // componentWillReceiveProps(nextProps){
    //     this.handelSetValue(nextProps);
    // }

    // 不可修改，父组件要通过getValue()获取值
    getValue = () => {
        const { members0, members1, members2 } = this.state;
        const outerMembers = members0.map(v => (this.filterKeys(v)));
        const innerMembers = [...members1, ...members2].map(v => (this.filterKeys(v)));
        return { outerMembers, innerMembers };
    }

    handelSetValue = (props) => {
        // 设置当前账号为默认成员
        const { info = {}, data = {}, create } = props;
        this.userid = window.localStorage.getItem('userId') - 0;

        let members0 = _.get(data, 'members', []) || []; // null的时候也会正常返回null 坑
        let members1 = [];
        let members2 = [];
        const clientMembers = _.get(data, 'info.client[0].members', []) || [];


        const currentUser = {
            ...info,
            ismanager: true, ishost: true,
            username: info.realname,
            userid: this.userid,
            grouptype: 2,
            innergrouptype: 0
        }

        if (clientMembers.length) {
            clientMembers.forEach(v => {
                if (v.innergrouptype === 1) members1.push(v);
                else if (v.innergrouptype === 2) members2.push(v);
            })
        }

        // 创建项目和项目编辑添加阶段的时候，默认添加当前登录用户
        this.isBoss = data.islawyerhost || data.islawyermanager;
        if (!members0.length && (create || (!create && this.isBoss))) members0 = [currentUser];
        if (!members2.length && (create || (!create && this.isBoss))) members2 = [{ ...currentUser, grouptype: 1, innergrouptype: 2 }]

        this.setBaseValue({ members0, members1, members2 });
    }

    setBaseValue = ({ members0, members1, members2 }) => {
        this.setState({ members0, members1, members2 });
    }

    // 更新数据
    updateData = (key, value) => {
        this.setState({ [key]: value });
    }

    handleMember = ({ domEvent, key }, v, i, activeKey) => {
        domEvent.stopPropagation();
        domEvent.preventDefault();

        const { create } = this.props;
        const { members0, members2 } = this.state;

        // 转移权限的限制处理
        // 律师协作团队和律师代理组的成员的权限必须一致
        const isLowyerChange = activeKey === 'members0' || activeKey === 'members2';
        if (isLowyerChange) {
            const isInBoth = members0.some(m => m.userid === v.userid) && members2.some(m => m.userid === v.userid);
            if (!isInBoth) {
                message.warn('律师组转移权限的时候，该成员必须同时是律师协作团队和律师代理组的成员');
                return;
            }
            // 限制创建项目的时候同时把权限都转移给其他人
            if (create) {
                const currentUser = this.state[activeKey][0];
                if (opts[key] === 'ishost' && !currentUser.ismanager) { // 要设置其它人为主办人
                    message.warn('创建阶段不可以把主办人和管理员权限都转移给其人人员');
                    return;
                } else if (opts[key] === 'ismanager' && !currentUser.ishost) { // 要设置其它人为管理人
                    message.warn('创建阶段不可以把主办人和管理员权限都转移给其人人员');
                    return;
                }
            }
        }
        // 先执行第一次更新
        this.handleMemberMethod(key, activeKey, v);
        // 再同步跟新另外一个律师组
        if (isLowyerChange) {
            const otherActiveKey = activeKey === 'members0' ? 'members2' : 'members0';
            const otherV = this.state[otherActiveKey].find(o => o.userid === v.userid);
            this.handleMemberMethod(key, otherActiveKey, otherV);
        }
    }

    handleMemberMethod = (key, activeKey, v) => {
        const { projectState, create, data } = this.props;
        if (!create) {
            projectState.manageMember({
                key,
                params: {
                    projectid: projectState.detailData.projectid,
                    stageid: data.stageid,
                    grouptype: v.grouptype,
                    innergrouptype: v.innergrouptype,
                    memberid: v.userid
                }
            }, () => {
                this.changeMember(key, activeKey, v);
            })
        } else this.changeMember(key, activeKey, v);
    }

    changeMember = (key, activeKey, v) => {
        const members = this.state[activeKey].concat();
        const newArr = members.map(m => ({ ...m, [opts[key]]: v.userid === m.userid }));
        // 再触发更新
        this.updateData(activeKey, newArr);
    }

    filterKeys = (v) => {
        return { userid: v.userid, username: v.username, grouptype: v.grouptype, innergrouptype: v.innergrouptype, ishost: v.ishost || false, ismanager: v.ismanager || false }
    }

    onOk = ({ targets: arrs }, callback) => {
        const { isAdd, activeKey } = this.state;
        let newArr = [];

        if (activeKey === 'members0') newArr = arrs.map(v => ({ ...v, innergrouptype: 0, grouptype: 2 }));
        else if (activeKey === 'members1') newArr = arrs.map(v => ({ ...v, innergrouptype: 1, grouptype: 1 }));
        else if (activeKey === 'members2') newArr = arrs.map(v => ({ ...v, innergrouptype: 2, grouptype: 1 }));

        const { projectState: { manageMember, detailData }, data, create } = this.props;
        const requestKey = isAdd ? 'addMember' : 'deleteMember';

        if (!create) {
            this.setState({ loading: true });
            manageMember({
                key: requestKey,
                params: {
                    projectid: detailData.projectid,
                    stageid: data.stageid,
                    grouptype: newArr[0].grouptype,
                    members: newArr,
                }
            }, () => {
                this.setState({ loading: false });
                this.handleOnOk(activeKey, newArr, isAdd);
                callback();
            })
        } else {
            this.handleOnOk(activeKey, newArr, isAdd);
            callback();
        }
    }

    handleOnOk = (activeKey, newArr, isAdd) => {
        const members = this.state[activeKey];
        let newMembers = [];

        if (isAdd) newMembers = [...members, ...newArr];
        else newMembers = members.filter(v => !newArr.some(s => s.userid === v.userid));

        // 默认第一个为委托人组的管理员
        if (activeKey === 'members1' && newMembers.length && !newMembers.some(v => v.ismanager)) newMembers[0].ismanager = true;

        this.updateData(activeKey, newMembers);
    }

    goPage = (key) => {
        // console.log(this.props);
        const { data } = this.props;
        const target = data[key];
        if (!target || !target.length || !target[0].groupid) {
            message.warn('该聊天组未创建');
            return;
        }
        const { ipcRenderer } = window.electron;
        ipcRenderer.send('set-goPage', { index: 0, data: { chatgroupid: target[0].groupid } });
    }

    render() {
        const { data, create, isShowInSlider } = this.props;
        const { showModal, activeKey, isAdd, members0, members1, members2 } = this.state;

        this.isBoss = data.islawyerhost || data.islawyermanager;
        this.isManager = this.isBoss || data.isclientmanager;

        const showClientChat = this.isBoss || [...members1, ...members2].some(v => v.userid === this.userid);
        const showLowyerChat = this.isBoss || members0.some(v => v.userid === this.userid);
        const isOnlyClient = members1.some(v => v.userid === this.userid);

        let showClientList = [...permissionList].slice(1); // 代理人列表只有管理员
        let showList = [...permissionList];
        let hasClientBtn = create;
        let hasBtn = create;

        if (!create) {
            if (!data.islawyerhost) showList = showList.slice(1);
            if (!data.islawyermanager) showList = showList.slice(0, showList.length - 1);

            if (!this.isManager) showClientList = [];

            hasClientBtn = this.isManager && !data.iscomplete;
            hasBtn = this.isBoss && !data.iscomplete;
        }

        const teams = [
            {
                groupname: "委托人协作团队",
                key: 'clientchatgroups',
                showChat: !create && showClientChat,
                groups: [
                    { name: '委托人组', members: members1, key: 'members1', hasBtn: hasClientBtn, showList: showClientList },
                    { name: '律师代理组', members: members2, key: 'members2', hasBtn, showList }
                ]
            },
            {
                groupname: "律师协作团队",
                key: 'lawyerchatgroups',
                showChat: !create && showLowyerChat,
                groups: [
                    { name: '', members: members0, key: 'members0', hasBtn, showList }
                ]
            }
        ]

        // 如果仅仅是代理人，整个律师协作团队都不显示
        if (!create && (isOnlyClient || !members0.length)) teams.pop();


        // 从不同组进去做筛选处理
        let selectMembers = this.state[activeKey];
        if (activeKey === 'members1' && isAdd) {
            selectMembers = [...members1, ...members2, ...members0];
        } else if (activeKey === 'members2' && isAdd) {
            selectMembers = [...members1, ...members2];
        } else if (activeKey === 'members0' && isAdd)
            if (activeKey === 'members0' && isAdd) {
                selectMembers = [...members1, ...members0];
            }

        return (
            <div>
                <div className={s.team}>
                    {teams.map(t => (
                        <div key={t.key} className={s.teamItem}>
                            <TitleItem
                                title={t.groupname}
                                icon={t.showChat && !isShowInSlider  && <span className={`mdi mdi-chat-processing mainColor ${s.chat}`} onClick={() => this.goPage(t.key)} />}
                                require={create}
                            />
                            {t.groups.map(g => (
                                <div key={g.key} className={s.gItem}>
                                    <div>{g.name}</div>
                                    <MemberList
                                        mainKey={g.key}
                                        showList={g.showList}
                                        members={g.members}
                                        hasBtn={g.hasBtn}
                                        handleMember={this.handleMember}
                                        onAdd={() => this.setState({ showModal: true, activeKey: g.key, isAdd: true })}
                                        onMinus={() => this.setState({ showModal: true, activeKey: g.key, isAdd: false })}
                                    />
                                </div>
                            ))}
                        </div>
                    ))}
                </div>
                <HandleMemberSelect
                    title={'成员'}
                    create={create}
                    isAdd={isAdd}
                    loading={this.state.loading}
                    data={data}
                    members={selectMembers}
                    onOk={this.onOk}
                    show={showModal}
                    onCancel={() => this.setState({ showModal: false })}
                />
            </div>
        )
    }
}

export default ProjectMember